# coding=utf-8
"""
    通用返回
"""
import json
import uuid
from flask import jsonify, current_app, Response
from base.res_msg import ResMsg


# @Time    :  2024-10-16 17:58:00
# @Author  :  jiangtong
# @Email   :  gingerqgyy@outlook.com
# @Project :  ginger_yl_test_boost
# @File    :  base_res


# 通用返回 :
def base_response(message='OK', code='OK', error_code=None, result=None, application='ginger-yl-test-boost'):
    """
    通用返回方法
    :param message: 响应信息
    :param code: 响应状态
    :param error_code: 错误状态
    :param result: 响应结果
    :param application: 应用标识
    :return: Json
    """
    response = {
        'message': message,
        'code': code,
        'errorCode': error_code,
        'result': result,
        'application': application,
        'traceId': str(uuid.uuid4()),
    }
    # 如果在 Flask 应用上下文中, 使用 jsonify 返回 :
    if current_app:
        current_app.logger.info(response)
        return jsonify(response), 200, {'Content-Type': 'application/json; charset=utf-8'}
    # 如果没有上下文, 直接使用 json.dumps 返回 :
    else:
        return json.dumps(response, ensure_ascii=False)


# 通用成功 :
def res_success(result=None):
    return base_response(*ResMsg.SUCCESS.value, result=result)


# 通用失败 :
def res_failure(result=None):
    return base_response(*ResMsg.FAILURE.value, result=result)


# 通用未找到 : ( 需要接受 e, 并且将 e 转为 str 进行响应, 否则报错 : [ TypeError: Object of type NotFound is not JSON serializable ] )
def res_not_found(e, ):
    return base_response(*ResMsg.NOT_FOUND.value, result=f'{e}')


# 通用参数校验失败 :
def res_param(result=None):
    return base_response(*ResMsg.PARAMETER_FAILED.value, result=result)


# 通用参数校验失败 :
def res_param_info(result=None):
    return base_response(*ResMsg.VALIDATION_FAILED.value, result=result)


# 权限校验失败 :
def res_un_auth(result=None):
    return base_response(*ResMsg.UNAUTHORIZED.value, result=result)


# 通用缺少 token :
def res_lose_token(result=None):
    return base_response(*ResMsg.UNAUTHORIZED.value, result=result)


# 通用返回 :
def res_base(message=None, result=None):
    return base_response(message=message, result=result)


if __name__ == '__main__':
    print(res_success())
    print(res_failure())
    print(res_not_found('Not Found Err'))
    print(res_success())
